var express = require('express');
var router = express.Router();
var Users = require("../../models/users.js");
var chkLogin = require("./filter/rules.js");

//加密
var crypto = require('crypto');
function md5 (text) {
    return crypto.createHash('md5').update(text).digest('hex');
};

//添加
//bug:未判断用户是否被占用
router.get("/users/add",chkLogin);
router.get("/users/add",function(req,res,next){
    res.render("admin/users/add",{
        user: req.session.user
    });
});
router.post("/users/add",chkLogin);
router.post("/users/add",function(req,res,next){
    var _user ={};
    for(var i in req.body){
        _user[i] = req.body[i];
    }
    //加密密码
    _user["password"] =md5(_user["password"]);
    var obj = new Users(_user);
    obj.save(function(err,users){
        var _json = {};
        if(err){ throw  err;
            _json.msg = "更新失败";
        }else{
            _json["succeed"] = true;
            _json.msg = "更新成功";
            _json.insertId = users.insertId;
        }
        res.send(_json);
    });
});

//列表
router.get("/users/list",chkLogin);
router.get("/users/list",function(req,res,next){
    var _pageSize= null,
        _pages =req.query.page?req.query.page:null;

    Users.getTen(_pageSize,_pages,function(err,users,totalPage){
        if(err){
            throw  err;
        }
        res.render("admin/users/list",{
            users:users,
            totalPage:totalPage,
            page:_pages,
            user: req.session.user
        });
    });
});

//编辑
router.get("/users/edit",chkLogin);
router.get("/users/edit",function(req,res,next){
    var _id = req.query.id;
    if(_id){
        var obj = new Users();
        obj.getOne(_id,function(err,users){
            if(err){throw err;}
            res.render("admin/users/edit",{
                users:users[0],
                user: req.session.user
            });
        });
    }
});
router.post("/users/edit",chkLogin);
router.post("/users/edit",function(req,res,next){
    var _users = {};
    for(var i in req.body){
        _users[i]= req.body[i];
    }
    //加密密码
    if(_users["password"]){
        _users["password"] =md5(_users["password"]);
    }
    var _json={};
    var obj = new Users(_users);
    obj.update(function(err,users){
       if(err){
           throw err;
           _json.msg="更新失败";
       } else{
           _json.msg="更新成功";
           _json.succeed=true;
       }
       res.send(_json);
    });
});

//删除
router.get("/users/delete",chkLogin);
router.get("/users/delete",function(req,res,next){
    var _id = req.query.id;
    if(_id){
        var obj = new Users();
        obj.delete(_id,function(err,users){
            if(err){throw err;}
            res.redirect("/admin/users/list")
        });
    }
});

module.exports = router;